package com.lwb.msmservice.controller;

import com.lwb.commonutils.Row;
import com.lwb.msmservice.service.MsmService;
import com.lwb.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public Row send(@PathVariable String phone){
        //1. 先从redis中获取验证码，如果取到直接返回
        String code = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(code)){
            return Row.SUCCESS();
        }
        //2. 如果Redis获取不到，就进行阿里云的发送
        //生成随机值，传递阿里云进行发送
        code  = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service中的方法进行发送
        boolean isSend = msmService.send(param, phone);
        if(isSend){
            //发送成功，把发送的验证码存入到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            return Row.SUCCESS();
        }else{
            return Row.ERROR().message("短信发送失败");
        }

    }

}
